package open.tech.dawn.web.util;

import lombok.extern.slf4j.Slf4j;
import open.tech.dawn.core.service.ICacheService;
import open.tech.dawn.core.util.SpringContextHolder;
import open.tech.dawn.ehcache.DefaultCacheServiceImpl;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;

@Component
@Slf4j
public class CacheUtil {

    private static ICacheService cacheService;

    @PostConstruct
    private void init() {
        try {
            cacheService = SpringContextHolder.getBean(ICacheService.class);
        } catch (Exception e) {
            log.warn("没有实现open.tech.dawn.core.service.ICacheService，采用默认的EhCache缓存");
            cacheService = new DefaultCacheServiceImpl();
        }
    }

    /**
     * 添加缓存
     *
     * @param cacheName         缓存名称
     * @param key               键
     * @param value             值
     * @param expirationSeconds 有效时间(单位: s)
     */
    public static void put(String cacheName, String key, Object value, int expirationSeconds) {
        cacheService.put(cacheName, key, value, expirationSeconds);
    }

    /**
     * 添加缓存
     *
     * @param cacheName 缓存名称
     * @param key       键
     * @param value     值
     */
    public static void put(String cacheName, String key, Object value) {
        cacheService.put(cacheName, key, value);
    }

    /**
     * 获取缓存
     *
     * @param cacheName 缓存名称
     * @param key       键
     * @return 返回
     */
    public static Object get(String cacheName, String key) {
        return cacheService.get(cacheName, key);
    }

    /**
     * 获取缓存
     *
     * @param cacheName 缓存名称
     */
    public static void remove(String cacheName) {
        cacheService.remove(cacheName);
    }

}
